package com.yanqu.road.server.gameplayer.module.activity.biaoju;

import com.yanqu.road.dao.impl.player.UserBiaoJuDaoImpl;
import com.yanqu.road.entity.activity.biaoju.UserBiaoJuData;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eMessageType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.activity.biaoju.BiaoJuConfig;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.BiaoJuProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.fund.ActivityFundModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.biaoju.BiaoJuConfigMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.maidian.biaoju.BiaoJuLog;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;

public class ActivityBiaoJuModule extends GeneralModule {
    public ActivityBiaoJuModule(GamePlayer player) {
        super(player);
    }

    private UserBiaoJuData userData;

    private boolean isWaitRefreshBack = false;

    @Override
    public boolean loadData() {
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            userData = new UserBiaoJuDaoImpl().getUserBiaoJuData(config.getActivityId(), getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                new UserBiaoJuDaoImpl().add(userData);
            } else if (userData.isUpdateOption()) {
                new UserBiaoJuDaoImpl().update(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if (!isSystemOpen()) {
            return;
        }
        initUserData();
        syncConfig();
        syncUserData();

        //每次登录请求一次跨服数据
        crossReqUserDataSync();
    }

    public boolean isSystemOpen() {
        return SystemOpenMgr.systemOpen(player, eSystemId.BiaoJu.getValue());
    }

    /**
     * 请求跨服的玩家数据同步回来,更新成就用
     */
    public void crossReqUserDataSync() {
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        if (userData != null) {
            int groupId = GameUnionActivityGroupMgr.getGroupId(userData.getActivityId(), player.getUserId());
            if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
                BiaoJuProto.CrossBiaoJuCommonReqMsg.Builder reqMsg = BiaoJuProto.CrossBiaoJuCommonReqMsg.newBuilder();
                reqMsg.setActivityId(userData.getActivityId());
                UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());
                reqMsg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                player.sendUnionActivityGroupPacket(CrossProtocol.C_BIAOJU_REQ_SYNC_USER_DATA, reqMsg, reqMsg.getActivityId(), groupId);
            }
        }
    }

    public void initSystemOpen() {
        if (!isSystemOpen()) {
            return;
        }
        initUserData();
        syncConfig();
        syncUserData();

        crossReqUserDataSync();
    }

    public void initUserData() {
        if (!isSystemOpen()) {
            return;
        }
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        synchronized (this) {
            if (userData == null || userData.getActivityId() != config.getActivityId()) {
                userData = new UserBiaoJuData(config.getActivityId(), getUserId());
            }
        }
    }

    public void syncConfig() {
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        BiaoJuProto.BiaoJuSyncConfigMsg.Builder configMsg = BiaoJuConfigMgr.getConfigMsg(player.getLanguage());
        player.sendPacket(ClientProtocol.U_BIAOJU_SYNC_CONFIG, configMsg);
    }

    public void syncUserData() {
        if (userData == null) {
            return;
        }

        BiaoJuProto.BiaoJuSyncUserDataMsg.Builder syncMsg = BiaoJuProto.BiaoJuSyncUserDataMsg.newBuilder();
        syncMsg.setActivityId(userData.getActivityId());
        syncMsg.setRefreshAmount(userData.getRefreshAmount());
        syncMsg.setGuaranteeAmount(userData.getGuaranteeAmount());
        syncMsg.setLastRefreshTime(userData.getLastRefreshTime());
        player.sendPacket(ClientProtocol.U_BIAOJU_SYNC_USER_DATA, syncMsg);
    }

    public UserBiaoJuData getUserData() {
        return userData;
    }

    public int buildCity(BiaoJuProto.BiaoJuCityBuildReqMsg reqMsg) {
        if (userData == null) {
            return GameErrorCode.E_BIAOJU_NOT_ABLE;
        }
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        long currentTime = DateHelper.getCurrentTime();
        if (currentTime >= config.getNowCityRankSettleTime()) {
            return GameErrorCode.E_BIAOJU_CITY_RANK_IN_SETTLE;
        }

        player.sendUnionActivityGroupPacket(CrossProtocol.C_BIAOJU_CITY_BUILD, reqMsg.toBuilder(), config.getActivityId());

        return 0;
    }

    public void buildCityBack(BiaoJuProto.BiaoJuCityBuildRespMsg respMsg) {
        if (respMsg.getRet() == 0) {
            userData.setMoney(respMsg.getUserInfo().getMoney());
            //更新成就
            player.notifyListener(eGamePlayerEventType.BiaoJuExp.getValue(), respMsg.getUserInfo().getExp());
            player.notifyListener(eGamePlayerEventType.BiaoJuUnionExpAdd.getValue(), respMsg.getUserInfo().getUnionExpAdd());
            player.getModule(ActivityFundModule.class).updateProgress(userData.getActivityId(), respMsg.getUnionInfo().getUnionExp());

            BiaoJuLog.traceBuildCity(player, userData.getActivityId(), respMsg);
        }

        player.sendPacket(ClientProtocol.U_BIAOJU_CITY_BUILD, respMsg.toBuilder());
    }

    public int speedUpEscort(int num) {
        if (userData == null) {
            return GameErrorCode.E_BIAOJU_NOT_ABLE;
        }
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        int speedupGoodsId = config.getSpeedupGoodsId();
        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(speedupGoodsId);
        if (goodsInfo == null) {
            return GameErrorCode.E_BAG_ITEM_NO_EXIST;
        }

        Property cost = new Property(speedupGoodsId, num);

        if (!player.getModule(CurrencyModule.class).currencyIsEnough(cost)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }

        player.getModule(PreReduceModule.class).preReduce(cost);

        BiaoJuProto.CrossBiaoJuSpeedUpEscortReqMsg.Builder crossReq = BiaoJuProto.CrossBiaoJuSpeedUpEscortReqMsg.newBuilder();
        crossReq.setActivityId(config.getActivityId());
        crossReq.setNum(num);
        crossReq.setPerSpeedUpTime(goodsInfo.getParamList().get(0).longValue() * DateHelper.MINUTE_MILLIONS);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_BIAOJU_SPEEDUP_ESCORT, crossReq, config.getActivityId());

        return 0;
    }

    public void speedUpEscortBack(BiaoJuProto.BiaoJuSpeedupEscortRespMsg respMsg) {
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            log.error("speedUpEscortBack config is null");
            return;
        }
        int speedupGoodsId = config.getSpeedupGoodsId();

        Property cost = new Property(speedupGoodsId, respMsg.getNum());
        player.getModule(PreReduceModule.class).restorePreReduce(cost);

        Property realCost = new Property(speedupGoodsId, respMsg.getRealUseNum());

        if (!player.getModule(CurrencyModule.class).removeCurrency(realCost, eLogMoneyType.BiaoJu, eLogMoneyType.BiaoJuSpeedUpCost)) {
            log.error("speedUpEscortBack removeCurrency failed");
        }

        player.sendPacket(ClientProtocol.U_BIAOJU_SPEEDUP_ESCORT, respMsg.toBuilder());
    }

    public int refreshEscortList() {
        if (userData == null) {
            return GameErrorCode.E_BIAOJU_NOT_ABLE;
        }
        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            return GameErrorCode.E_BIAOJU_NOT_ABLE;
        }

        long currentTime = DateHelper.getCurrentTime();
        if (!DateHelper.isSameDay(currentTime / 1000, userData.getLastRefreshTime() / 1000)) {
            //跨天
            userData.setRefreshAmount(0);
            userData.setGuaranteeAmount(0);
            userData.setLastRefreshTime(currentTime);
            syncUserData();

            isWaitRefreshBack = false;
        }

        if (isWaitRefreshBack) {
//            return GameErrorCode.E_BIAOJU_WAIT_REFRESH_BACK;
        }

        if (userData.getRefreshAmount() >= config.getRefreshNumMax()) {
            return GameErrorCode.E_BIAOJU_REFRESH_NUM_MAX;
        }

        boolean isCost = false;
        if (userData.getRefreshAmount() >= config.getFreeRefreshNum()) {
            //免费次数用完要消耗道具
            isCost = true;
            if (!player.getModule(CurrencyModule.class).currencyIsEnough(config.getRefreshCost(userData.getRefreshAmount()))) {
                return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            }
        }

        isWaitRefreshBack = true;
        BiaoJuProto.CrossBiaoJuRefreshEscortReqMsg.Builder crossReq = BiaoJuProto.CrossBiaoJuRefreshEscortReqMsg.newBuilder();
        crossReq.setActivityId(config.getActivityId());
        crossReq.setIsCostGoods(isCost);

        player.sendUnionActivityGroupPacket(CrossProtocol.C_BIAOJU_REFRESH_ESCORT_LIST, crossReq, config.getActivityId());
        return 0;
    }

    public void refreshEscortListBack(BiaoJuProto.CrossBiaoJuRefreshEscortRespMsg respMsg) {
        isWaitRefreshBack = false;

        if (respMsg.getRespMsg().getRet() != 0) {
            player.sendPacket(ClientProtocol.U_BIAOJU_REFRESH_ESCORT_LIST, respMsg.getRespMsg().toBuilder());
            return;
        }

        BiaoJuConfig config = BiaoJuConfigMgr.getConfig();
        if (config == null) {
            log.error("refreshEscortListBack config is null");
            return;
        }


        if (respMsg.getIsCostGoods()) {
            if (!player.getModule(CurrencyModule.class).removeCurrency(config.getRefreshCost(userData.getRefreshAmount()), eLogMoneyType.BiaoJu, eLogMoneyType.BiaoJuRefreshCost)) {
                log.error("refreshEscortListBack removeCurrency fail");
            }
        }

        userData.setRefreshAmount(userData.getRefreshAmount() + 1);
        userData.setGuaranteeAmount(respMsg.getGuaranteeAmount());
        userData.setLastRefreshTime(DateHelper.getCurrentTime());

        syncUserData();

        player.sendPacket(ClientProtocol.U_BIAOJU_REFRESH_ESCORT_LIST, respMsg.getRespMsg().toBuilder());

        BiaoJuLog.traceRefresh(player, userData.getActivityId(), respMsg);
    }

    public void syncRedPoint(int canJoin) {
        BiaoJuProto.BiaoJuSyncUserRedPointMsg.Builder syncMsg = BiaoJuProto.BiaoJuSyncUserRedPointMsg.newBuilder();
        syncMsg.setCanJoin(canJoin);
        player.sendPacket(ClientProtocol.U_BIAOJU_SYNC_USER_RED_POINT, syncMsg);
    }

    public void takeEscortBack(BiaoJuProto.BiaoJuTakeEscortRespMsg respMsg) {

        userData.setRefreshAmount(0);
        syncUserData();

        WorldMessageProto.WorldMessageTempMsg.Builder chatMsg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
        chatMsg.setType(eMessageType.BiaoJuUnionEscort.getValue());
        chatMsg.setSendTime(DateHelper.getCurrentSecond());
        chatMsg.setUserId(player.getUserId());
        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId());
        if (null != userBaseInfo) {
            chatMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        }
        if (respMsg.getIsBest()) {//优化,优镖才推送
            //唯一标识
            String params = String.valueOf(respMsg.getEscortInfo().getSimpleInfo().getEscortUniqueId());
            chatMsg.setExtraParams(params);

            String unionUid = GameUnionActivityGroupMgr.getUnionUid(BiaoJuConfigMgr.getConfig().getActivityId(), player.getUserId());

            WorldMessageMgr.sendUnionChat(unionUid, chatMsg);
        }
    }
}
